package cn.sdjzu.exercise;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import com.dwin.navy.serialportapi.SerialPortOpt;

@SuppressLint({ "ShowToast", "WorldReadableFiles", "HandlerLeak" })
public class ConfigSerialPortActivity extends BasedActivity {
	public byte[] SET_SETTING_FORCE_PREFIX;
	@SuppressWarnings("unused")
	private Toast TestTransToast, cancelTrans;
	private SerialPortOpt serialPort;
	private OutputStream os;
	private InputStream is;
	private static final String[] Sserialport = { "COM0", "COM1", "COM2",
			"COM4" };
	private static final int[] m_iSerialPort = { 0, 1, 2, 4 };
	private static final String[] Sbaudrate = { "115200", "57600", "38400",
			"19200", "9600", "4800", "2400", "1200", "300", };
	private static final int[] baudrate = { 115200, 57600, 38400, 19200, 9600,
			4800, 2400, 1200, 300, };
	private static final String[] Sdatabits = { "5", "6", "7", "8" };
	private static final int[] databits = { 5, 6, 7, 8 };
	private static final String[] Sstopbits = { "1", "2", };
	private static final int[] stopbits = { 1, 2, };
	private static final String[] Sparity = { "None", "Odd", "Even", "Mark",
			"Space" };
	private static final int[] parity = { 'n', 'o', 'e', 'm', 's' };
	private Spinner spiChooseSerialPort;
	private Spinner spiChooseBaudRate;
	private Spinner spiChooseDataBits;
	private Spinner spiChooseStopBits;
	private Spinner spiChooseParity;
	private Button conn;
	private Button cancel;
	private ArrayAdapter<String> adapSerialPort;
	private ArrayAdapter<String> adapBaudRate;
	private ArrayAdapter<String> adapDataBits;
	private ArrayAdapter<String> adapStopBits;
	private ArrayAdapter<String> adapParity;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ExerciseApp.getInstance().addActivity(this);
		setContentView(R.layout.serialportconfig);
		spiChooseSerialPort = (Spinner) findViewById(R.id.COM);
		spiChooseBaudRate = (Spinner) findViewById(R.id.inputSpeed);
		spiChooseDataBits = (Spinner) findViewById(R.id.inputDataBits);
		spiChooseStopBits = (Spinner) findViewById(R.id.inputStopBits);
		spiChooseParity = (Spinner) findViewById(R.id.inputParity);
		conn = (Button) findViewById(R.id.getSeialPort23);
		cancel = (Button) findViewById(R.id.NogetSeialPort);
		serialPort = new SerialPortOpt();
		preferences = getSharedPreferences("itYao", Context.MODE_WORLD_READABLE);
		editor = preferences.edit();
		TransToast = Toast.makeText(getApplicationContext(),
				"连接失败,请检查端口或者重新选择通讯方式！", Toast.LENGTH_LONG);
		TestTransToast = Toast.makeText(getApplicationContext(), "连接成功！",
				Toast.LENGTH_LONG);
		cancelTrans = Toast.makeText(getApplicationContext(),
				"未配置通讯，不能进行训练！！！", Toast.LENGTH_LONG);
		SET_SETTING_FORCE_PREFIX = new byte[] { (byte) 0x01, (byte) 0x10,
				(byte) 0x00, (byte) 0x6D, (byte) 0x00, (byte) 0x01,
				(byte) 0x02, };
		adapSerialPort = new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, Sserialport);
		adapSerialPort
				.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		adapBaudRate = new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, Sbaudrate);
		adapBaudRate
				.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		adapDataBits = new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, Sdatabits);
		adapDataBits
				.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		adapStopBits = new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, Sstopbits);
		adapStopBits
				.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		adapParity = new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, Sparity);
		adapParity
				.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		spiChooseSerialPort.setAdapter(adapSerialPort);
		spiChooseBaudRate.setAdapter(adapBaudRate);
		spiChooseDataBits.setAdapter(adapDataBits);
		spiChooseStopBits.setAdapter(adapStopBits);
		spiChooseParity.setAdapter(adapParity);
		spiChooseSerialPort.setSelection(0);
		spiChooseBaudRate.setSelection(0);
		spiChooseDataBits.setSelection(3);
		spiChooseStopBits.setSelection(1);
		spiChooseParity.setSelection(0);
		serialPort.mDevNum = m_iSerialPort[0];
		serialPort.mSpeed = baudrate[0];
		serialPort.mDataBits = databits[3];
		serialPort.mStopBits = stopbits[1];
		serialPort.mParity = parity[0];
		spiChooseSerialPort
				.setOnItemSelectedListener(new SpiOnItemSelectedListenerImpl());
		spiChooseBaudRate
				.setOnItemSelectedListener(new SpiOnItemSelectedListenerImpl());
		spiChooseDataBits
				.setOnItemSelectedListener(new SpiOnItemSelectedListenerImpl());
		spiChooseStopBits
				.setOnItemSelectedListener(new SpiOnItemSelectedListenerImpl());
		spiChooseParity
				.setOnItemSelectedListener(new SpiOnItemSelectedListenerImpl());
		conn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ConnThread connt = new ConnThread();
				connt.start();
			}
		});
		cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				cancelTrans.show();
				Intent intent = new Intent(ConfigSerialPortActivity.this,
						ControlPanelActivity.class);
				startActivity(intent);
				ConfigSerialPortActivity.this.finish();
				onDestroy();
			}
		});
	}

	class ConnThread extends Thread {
		@Override
		public void run() {
			openSerialPort();
		}
	}
	private void openSerialPort() {
		serialPort.openDev(serialPort.mDevNum);
		serialPort.setSpeed(serialPort.mFd, serialPort.mSpeed);
		serialPort.setParity(serialPort.mFd, serialPort.mDataBits,
				serialPort.mStopBits, serialPort.mParity);
		is = serialPort.getInputStream();
		os = serialPort.getOutputStream();
		if (serialPort.mFd.valid()==true) {
			try {
				os.write(CRCChecker.getFinalSendBytes(SET_SETTING_FORCE_PREFIX,
						100));
			} catch (Exception e) {
				e.printStackTrace();
			}
			//TestTransToast.show();
			editor.putString("TransmissionWay", "selectSerialport");
			editor.putInt("com", serialPort.mDevNum);
			editor.putInt("speed", serialPort.mSpeed);
			editor.putInt("DataBits", serialPort.mDataBits);
			editor.putInt("StopBits", serialPort.mStopBits);
			editor.putInt("Parity", serialPort.mParity);
			editor.commit();
		} else {
			TransToast.show();
		}
		Intent intent = new Intent(ConfigSerialPortActivity.this,
				ControlPanelActivity.class);
		startActivity(intent);
		//ConfigSerialPortActivity.this.onDestroy();
		ConfigSerialPortActivity.this.finish();

	}

	protected void closeSerialPort() {
		try {
			is.close();
			os.close();
			serialPort.closeDev(serialPort.mFd);
			serialPort = null;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onResume() {
		super.onResume();

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (is != null) {
			closeSerialPort();
		} else {
			serialPort = null;
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@SuppressWarnings("unused")
	private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context arg0, Intent arg1) {
			finish();
		}
	};

	public void onBackPressed() {
		close();
	}

	private class SpiOnItemSelectedListenerImpl implements
			OnItemSelectedListener {
		@Override
		public void onNothingSelected(AdapterView<?> parent) {
		}

		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			if (parent == spiChooseSerialPort) {
				serialPort.mDevNum = m_iSerialPort[position];
				// tViewSerialPort.setText(Sserialport[position]);
				Log.i("uart params set", "ChooseSerialPort_"
						+ serialPort.mDevNum);
			} else if (parent == spiChooseBaudRate) {
				serialPort.mSpeed = baudrate[position];
				// tViewBaudRate.setText(Sbaudrate[position]);
				Log.i("uart params set", "ChooseBaudRate_" + serialPort.mSpeed);

			} else if (parent == spiChooseDataBits) {
				serialPort.mDataBits = databits[position];
				Log.i("uart params set", "ChooseDataBits_"
						+ serialPort.mDataBits);
			} else if (parent == spiChooseStopBits) {
				serialPort.mStopBits = stopbits[position];
				Log.i("uart params set", "ChooseStopBits_"
						+ serialPort.mStopBits);
			} else if (parent == spiChooseParity) {
				serialPort.mParity = parity[position];
				Log.i("uart params set", "ChooseParity_" + serialPort.mParity);
			}
			if (serialPort.mFd != null) {
				serialPort.setSpeed(serialPort.mFd, serialPort.mSpeed);
				Log.i("uart port operate", "====>here...uart set speed..."
						+ serialPort.mSpeed);
				serialPort.setParity(serialPort.mFd, serialPort.mDataBits,
						serialPort.mStopBits, serialPort.mParity);
				Log.i("uart port operate", "====>here...uart other params..."
						+ serialPort.mDataBits + "..." + serialPort.mStopBits
						+ "..." + serialPort.mParity);
			}
		}
	}
}
